package com.ruoyi.coal.modules.coal.controller;

import com.ruoyi.coal.common.utils.R;
import com.ruoyi.coal.modules.coal.service.ObjService;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/scan/"})
public class ObjController {
    @Autowired
    ResourceLoader loader;

    @Autowired
    ObjService objService;

    @GetMapping({"/startRadar"})
    public R startRadar() {
        String volume = this.objService.startRadar();
        return R.ok().put("volume", volume);
    }

    @GetMapping({"/data"})
    public R list() {
        String volume = this.objService.getVolume();
        return R.ok().put("volume", volume);
    }

    @GetMapping({"/getFile"})
    public ResponseEntity<byte[]> getFile() throws IOException {
        String filePath = this.objService.getObj();
        InputStream inputStream = this.loader.getResource("file:" + filePath).getInputStream();
        byte[] body = IOUtils.toByteArray(inputStream);
        String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        inputStream.close();
        return new ResponseEntity(body, (MultiValueMap)headers, HttpStatus.OK);
    }
}

